import pathIcon from '@/assets/path.png';
import SenderChat from '@/components/SenderChat';
import {
  conversationList,
  describePageStructure,
  getDetail,
  getDropDownList,
  getProjectList,
  queryMessagesByConversationId,
} from '@/services/chat';
import { CheckOutlined } from '@ant-design/icons';
import { Attachments, useXAgent, useXChat } from '@ant-design/x';
import { Flex, Layout, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import BubbleList from './Components/BubbleList';
import ChatArea from './Components/ChatArea';
import HistoryModal from './Components/HistoryModal'; // 历史对话框
import Preview from './Components/Preview';
import Sidebar from './Components/Sidebar'; // 侧边栏
import styles from './index.less';

const { Sider } = Layout;

const ChatInterface: React.FC = () => {
  const [collapsed, setCollapsed] = useState(true);
  const [historyModalVisible, setHistoryModalVisible] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const [isModelLoading, setIsModelLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [sationList, setSationList] = useState<any[]>([]);
  const [projectList, setProjectList] = useState<any[]>([]);
  const [dropDownList, setDropDownList] = useState<any[]>([]);
  const [versions, setVersions] = useState<any>([]);
  const [versionNum, setVersionNum] = useState<string>('');
  const [programInfo, setProgramInfo] = useState<any>({});
  const [requireInfo, setRequireInfo] = useState<any>({});
  const [detailInfo, setDetailInfo] = useState<any>({});
  const ref: any = useRef(null);

  // 初始化查询历史对话记录
  const init = async () => {
    const { code, data } = await conversationList({});
    if (code === 200) {
      setSationList(data.list);
    }
  };

  const initProjectList = async () => {
    const { code, data } = await getProjectList({});
    if (code === 200) {
      setProjectList(data);
    }
  };

  const initDropDownList = async () => {
    const { code, data } = await getDropDownList({});
    if (code === 200) {
      setDropDownList(data);
    }
  };

  useEffect(() => {
    init();
    initProjectList();
    initDropDownList();
  }, []);

  const chatCallBack = async (res: any) => {
    if (res.code !== 200) {
      message.error(res.msg);
      return;
    }
  };

  const [agent] = useXAgent({
    request: async (info, callbacks) => {
      const { messages, message } = info as any;
      const { onSuccess, onUpdate, onError } = callbacks;
      let content: string = '';
      const imageUrls = message.images;
      const imgUrl =
        imageUrls?.find((ele: any) => ['image'].includes(ele.type))?.url || '';
      let isFirstChunk = true;
      if (message.text === '设计稿正在生成中，请稍等...') {
        setIsModelLoading(true); // 开始加载
        return;
      }
      onUpdate('好的');
      setIsExpanded(true);
      setIsModelLoading(true); // 开始加载
      try {
        const res: any = await describePageStructure({
          conversationId: ref.conversationId || '',
          textMessage: message.text,
          imageUrls: imgUrl ? [imgUrl] : [],
          projectId: ref.programId,
          requirementId: ref.requireId,
        });

        chatCallBack(res);

        ref.conversationId = res.data.conversationId;
        const stream: any = Array.from(res.data.answer);
        for await (const chunk of stream) {
          const newContent = chunk;
          content += newContent;
          if (newContent) {
            if (isFirstChunk) {
              isFirstChunk = false;
            }
            onUpdate(content);
          }
          await new Promise((resolve) => setTimeout(resolve, 50));
        }
        onSuccess(content);
        setIsModelLoading(false); // 加载完成
        setIsExpanded(false);
      } catch (error: any) {
        console.error(error);
        setIsModelLoading(false); // 加载完成
        setIsExpanded(false);
        onError(error);
      }
    },
  });

  const { onRequest, messages, setMessages } = useXChat({
    agent,
  });

  const toggleSidebar = () => {
    setCollapsed(!collapsed);
  };

  const handleRecord = () => {
    setHistoryModalVisible(true);
  };

  const handleHistoryModalCancel = () => {
    setHistoryModalVisible(false);
  };

  const handleHistoryModalConfirm = () => {
    // 处理确认逻辑
    setHistoryModalVisible(false);
  };

  // 跟大模型对话
  const handleChat = async (params: any) => {
    setOpen(true);
    const images = await Promise.all(
      params.fileList.map(async (item: any) => ({
        name: item.name,
        url: item.imageUrl || '',
        type: item.type.startsWith('image/') ? 'image' : 'file',
      })),
    );
    console.log('images=>>>>>>>12313', images);
    try {
      // 首先添加用户的文本消息
      onRequest({
        text: params.value,
        role: 'user',
        images,
        footer: (
          <>
            <Flex gap="middle" className={styles.down}>
              {params.fileList.map((file: any, index: number) => (
                <Attachments.FileCard key={index} item={file} />
              ))}
            </Flex>
          </>
        ),
      } as any);
    } catch (error) {
      console.error('Error processing images:', error);
    }
  };

  const aiFooter = () => {
    return (
      <div className={styles.aiFooter}>
        <div className={styles.aiItem}>
          <div className={`${styles.icon} ${styles.success}`}>
            <CheckOutlined />
          </div>
          <span className={styles.aiText}>需求理解已完成</span>
        </div>
        <div className={styles.aiItem}>
          <div className={`${styles.icon} ${styles.pending}`}>2</div>
          <span className={styles.aiText}>正在生成demo</span>
        </div>
      </div>
    );
  };

  // 点击去生成代码按钮
  const handleEditClick = (content: string) => {
    // 这里你可以打开一个编辑模态框或者跳转到编辑页面
    const newImageMessage: any = messages.findLast(
      (msg: any) => msg.message.images && msg.message.images.length > 0,
    );
    const info = newImageMessage?.message?.images?.find(
      (item: any) => item.type === 'image',
    );

    onRequest({
      text: '设计稿正在生成中，请稍等...',
      role: 'ai',
      image: info?.url || '',
      footer: aiFooter(),
    } as any);
    setIsExpanded(true);
  };

  // 查看预览
  const handleGoToPreview = () => {
    setShowPreview(true);
  };

  // 返回对话页面
  const handleBack = () => {
    setShowPreview(false);
  };

  // 新建对话
  const handleNewChat = () => {
    if (!open) {
      message.success('当前已经是新对话啦！');
    }
    setOpen(false);
  };

  const handleHistoryData = (data: any) => {
    const newversions: any = [];
    return data.map((item: any, index: number) => {
      const { fromSource, query, answer, message, pagePath, version } = item;
      const msg = message ? JSON.parse(message) : '';
      const file = {
        uid: '10',
        name: 'image-file.jpg',
        thumbUrl: msg?.imageUrls?.[0] || '',
        url: msg?.imageUrls?.[0] || '',
        size: 123456,
      };
      if (fromSource === 'user') {
        return {
          message: {
            text: query,
            role: 'user',
            ...(msg?.imageUrls?.length > 0 && {
              footer: (
                <>
                  <Flex gap="middle" className={styles.down}>
                    <Attachments.FileCard item={file} />
                  </Flex>
                </>
              ),
            }),
          },
          status: 'success',
        };
      } else {
        if (pagePath) {
          newversions.push({
            version: version,
            name: version,
            desc: `${version}版本`,
            url: pagePath,
          });
          setVersions(newversions);
          return {
            message: {
              text: '设计稿已完成，请点击查看',
              footer: (
                <div
                  className={styles.versionCode}
                  onClick={handleGoToPreview}
                  // style={{
                  //   backgroundImage: `url(${img})`,
                  // }}
                >
                  <span className={styles.version}>{version}</span>
                </div>
              ),
            },
            status: 'success',
          };
        } else {
          return {
            message: answer,
            status: 'success',
          };
        }
      }
    });
  };

  // 查看历史对话
  const handleClickSation = async (item: any) => {
    setShowPreview(false);
    setVersions([]);

    const details = await getDetail(item.id);

    if (details.code === 200) {
      setDetailInfo(details.data);
    }

    ref.conversationId = item.id;
    const { code, data } = await queryMessagesByConversationId({
      conversationId: item.id,
    });
    if (code === 200) {
      const newData = handleHistoryData(data);
      setMessages(newData);
      setOpen(true);
    }
  };

  useEffect(() => {
    console.log('detailInfo=>>>>>', detailInfo);
    if (Object.keys(detailInfo).length > 0) {
      setProgramInfo(detailInfo.project);
      setRequireInfo(detailInfo.requirement);
    }
  }, [detailInfo]);

  // 删除数据之后的回调
  const handleDelCallBack = async () => {
    init();
  };

  const handleModelLoading = async (
    state: boolean,
    isError: boolean,
    isSuccess: boolean,
  ) => {
    setIsModelLoading(state);
    setIsExpanded(state);
    if (isError) {
      // 生成代码失败
      const newMessages = messages.map((ele: any) => {
        if (
          typeof ele.message !== 'string' &&
          ele.message.text.includes('设计稿正在生成中，请稍等...')
        ) {
          return {
            ...ele,
            message: {
              ...ele.message,
              text: '设计稿生成失败',
            },
          };
        } else {
          return ele;
        }
      });
      setMessages(newMessages);
    }

    if (isSuccess) {
      // 生成代码成功
      const newMessages = messages.map((ele: any) => {
        if (
          typeof ele.message !== 'string' &&
          ele.message.text.includes('设计稿正在生成中，请稍等...')
        ) {
          return {
            ...ele,
            message: {
              ...ele.message,
              text: '设计稿已完成，请点击查看',
              footer: (
                <div
                  className={styles.versionCode}
                  onClick={handleGoToPreview}
                  // style={{
                  //   backgroundImage: `url(${img})`,
                  // }}
                >
                  <span className={styles.version}>{versionNum}</span>
                </div>
              ),
            },
          };
        } else {
          return ele;
        }
      });
      setMessages(newMessages);
    }
  };

  // 选择项目
  const handleProgram = (vals: any) => {
    const info = projectList.find((ele) => ele.id === vals);
    setProgramInfo(info);
    ref.programId = vals;
  };

  // 选择需求
  const handleRequire = (vals: any) => {
    const info = dropDownList.find((ele) => ele.id === vals);
    setRequireInfo(info);
    ref.requireId = vals;
  };

  return (
    <div className={styles.chatInterface}>
      {/* 侧边栏 */}
      <Sider
        width={240}
        className={`${styles.sider} ${collapsed ? styles.collapsed : ''}`}
        collapsed={collapsed}
        collapsedWidth={0}
      >
        <Sidebar
          onRecord={handleRecord}
          onNewChat={handleNewChat}
          onClick={handleClickSation}
          isExpanded={isExpanded}
          sationList={sationList}
        />
      </Sider>
      {/* 右侧内容区 */}
      <div className={styles.rightContent}>
        <div className={styles.up}>
          {/* 切换按钮 */}
          <img
            src={pathIcon}
            className={`${styles.icon} ${!collapsed ? styles.iconShifted : ''}`}
            onClick={toggleSidebar}
          />
          {open && (
            <>
              <div className={styles.textword}>
                <span className={styles.label}>
                  {programInfo.name ? `${programInfo.name}--` : ''}
                </span>
                <span className={styles.value}>{requireInfo.title}</span>
              </div>
              <div className={styles.titleCode}>
                生成自动化营销CMS页面Prompt
              </div>
            </>
          )}
        </div>

        {/* 内容区域 */}
        <div
          className={`${styles.content} ${
            collapsed ? styles.contentShifted : ''
          }`}
        >
          {showPreview ? (
            <Preview onBack={handleBack} versions={versions} />
          ) : (
            <>
              {open ? (
                <BubbleList // 对话框
                  messages={messages}
                  isExpanded={isExpanded}
                  isModelLoading={isModelLoading}
                  onClick={handleEditClick}
                  setIsModelLoading={handleModelLoading}
                  onPreview={handleGoToPreview}
                  conversationId={ref.conversationId}
                  versions={versions}
                  onVersion={setVersions}
                  onVersionNum={setVersionNum}
                />
              ) : (
                <ChatArea
                  onChat={handleChat}
                  isExpanded={isExpanded}
                  projectList={projectList}
                  dropDownList={dropDownList}
                  onProgramChange={handleProgram}
                  onRequireChange={handleRequire}
                />
              )}
              {open && (
                <SenderChat
                  onChat={handleChat}
                  isHeightAuto={true}
                  isExpanded={isExpanded}
                />
              )}
            </>
          )}
        </div>
      </div>

      {/* 历史对话框 */}
      <HistoryModal
        visible={historyModalVisible}
        projectList={projectList}
        dropDownList={dropDownList}
        onCancel={handleHistoryModalCancel}
        onConfirm={handleHistoryModalConfirm}
        onDelCallBack={handleDelCallBack}
      />
    </div>
  );
};

export default ChatInterface;
